export default {
	namespaced: true,
	state() {
		return {
			cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		}
	},
	mutations: {
		addGoodsToCart(state, goods) {
			const findGoods = state.cart.find(item => item.goods_id === goods.goods_id)
			if (findGoods) {
				//如果添加的商品已存在 添加数量
				findGoods.goods_count++
			} else {
				// 不存在 则添加商品
				state.cart.push(goods)
			}
			this.commit('cart/saveToStorage')
		},
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify((state.cart)))
		},
		updataGoodsSate(state, goods) {
			console.log(goods);
			state.cart.some(item => {
				if (item.goods_id === goods.goods_id) {
					item.goods_state = !goods.goods_state

					return true
				}
			})
			this.commit('cart/saveToStorage')
		},
		changeGoodsCount(state, goods) {
			console.log(goods);
			// console.log(num);
			state.cart.some(item => {
				if (item.goods_id === goods.goods_id) {
					if (goods.goods_id == 0) {
						console.log('商品数量=0')
						this.delGoodsById(item.goods_id)
						this.commit('cart/delGoodsById', item.goods_id)
					}
					item.goods_count = goods.goods_count
					return true
				}
			})
			this.commit('cart/saveToStorage')
		},
		delGoodsById(state, goods_id) {
			const index = state.cart.findIndex(item => item.goods_id === goods_id)
			state.cart.splice(index, 1)
			this.commit('cart/saveToStorage')
		},
		updateAllGoods_state(state, goods_state) {
			state.cart.forEach(goods => goods.goods_state = goods_state)
			this.commit('cart/saveToStorage')
		}
	},
	getters: {
		total(state) {
			return state.cart.reduce((sum, goods) => sum += goods.goods_count, 0)
		},
		//结算的数据的数量
		totals(state) {
			const arr = state.cart.filter(item => item.goods_state === true)
			return arr.reduce((sum, goods) => sum += goods.goods_count, 0)
		}, //总价
		totalprice(state) {
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item
				.goods_price, 0).toFixed(2)
		},
		goods(state) {
			return state.cart.reduce((list, goods) => {
				if (goods.goods_state) {
					list.push({
						goods_id: goods.goods_id,
						goods_number: goods.goods_count,
						goods_price: goods.goods_price
					})
					return list
				}
				return list
			}, [])
		}
	}
}
